import React, { useEffect, useState, ChangeEvent, useRef } from 'react';
import './../login/Login.scss';
import { BrowserRouter, Routes, Route, Link, Navigate, useNavigate } from 'react-router-dom'
import { Button, Space, Segmented, Input, Checkbox } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { UserOutlined, RightOutlined, SafetyCertificateOutlined, MobileOutlined, LockOutlined, LoadingOutlined } from '@ant-design/icons';
import { SegmentedValue } from 'antd/es/segmented';
import { getChangeEventValue, toastShort } from '../../utils';
import systemApi from '../../api/system';

const Register = () => {

    const [phone, setPhone] = useState('');
    const [account, setAccount] = useState('');
    const [password, setPassword] = useState('');
    const [code, setCode] = useState('');
    const [codeLoading, setCodeLoading] = useState(false);
    const [isShow, setShow] = useState(true);
    const [codeSending, setCodeSending] = useState(true);
    const [loginLoading, setLoginLoading] = useState(false);
    const [countTime, setCountTime] = useState<number>(59);
    const [loginMethod, setLoginMethod] = useState<SegmentedValue>('手机验证码登录');
    const countTimeRef = useRef<number>(59);
    const delayTimer = useRef<any>(null);

    const navigate = useNavigate();

    const jumpTest = () => {
        navigate('/')
    };

    const onChange = (e: CheckboxChangeEvent) => {
        console.log(`checked = ${e.target.checked}`);
    };

    const onPhoneTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        if (getChangeEventValue(e).length > 11) {
            return toastShort('warning', '手机号最长不超过11位')
        }
        setPhone(getChangeEventValue(e))
    }

    const onCodeTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        setCode(getChangeEventValue(e))
    }

    const onAccountTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        setAccount(getChangeEventValue(e))
    }

    const onPasswordTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        if (getChangeEventValue(e).length > 20) {
            return toastShort('warning', '密码超过20位')
        }
        setPassword(getChangeEventValue(e))
    }


    const checkLoginBtnEnable = (): boolean => {
        let loginBtnEnable = false;
        if (phone.length == 11 && code.length == 4 && password.length > 0) {
            loginBtnEnable = true;
        }
        return loginBtnEnable;
    };

    const handleSendCode = () => {
        if (phone.length == 0) {
            return toastShort('error', '请输入手机号')
        }
        if (phone.length !== 11) {
            return toastShort('error', '请输入合法的手机号')
        }
        if (codeLoading) {
            return false;
        }
        setCodeLoading(true);
        setCodeSending(true)
        delayTimer.current = setTimeout(() => {
            setCodeSending(false);
            startCountDown();
            toastShort('success', '验证码已发送，请查收')
        }, 2000);
    }

    const startCountDown = () => {
        if (countTimeRef.current == 0) {
            console.log("倒计时结束------->");
            setCodeLoading(false);
            setCodeSending(true);
            countTimeRef.current = 59;
            setCountTime(59);
            return false;
        }
        delayTimer.current = setTimeout(() => {
            const newCountTime = countTimeRef.current - 1;
            setCountTime(newCountTime);
            countTimeRef.current = newCountTime;
            startCountDown();
        }, 1000)
    }

    const jumpToLogin = () => {
        navigate('/login')
    }

    const onLoginMethodChange = (e: SegmentedValue) => {
        console.log("onLoginMethodChange---->", e);
        setLoginMethod(e);
    };

    useEffect(() => {
        console.log("初始化----register")
    }, [])

    const handleRegister = () => {
        if (password.length < 8) {
            return toastShort('warning', '密码不少于8位')
        }
        var re = /^(?=.*[a-z])(?=.*\d)[^]{8,16}$/;
        var result = re.test(password);
        if (!result) {
            return toastShort('error', "密码必须包含数字,字母,且不少于8位");
        }
        let params = {
            phone: phone,
            password: password,
            code: code,
        };
        setLoginLoading(true)
        systemApi.register(params)
            .then(res => {
                console.log("login--res", res)
                setLoginLoading(false);
                navigate('/')
            })
            .catch(err => {
                setLoginLoading(false)
                console.log("login--err", err)
            })
    }

    return (
        <div className='login-page'>
            <div className='login-left'>
                <div className='login-img'></div>
                <div className='login-left-info'>
                    <div className='flex-row login-left-title'><span style={{ fontSize: '36px', marginRight: "10px" }} className="iconfont ghzs-color-logo"></span><span>自然保护地规划智慧辅助系统</span></div>
                    <div className='login-left-explain'>
                        <div className='login-left-text'>自然保护地规划智慧辅助系统是一款为专门为保护地规划编制开发的产品。表文联动带来了便捷的编制体验，智能推荐大大提升工作效率、实时文档保存，所见即所得的预览等功能，帮助您安全稳定地导出规划文档，让一切变得简单高效！</div>
                        <div className='login-left-list'>
                            <div className='flex-row'><span className='iconfont-1 ghzs-gray-highlight' />表文联动</div>
                            <div className='flex-row'><span className='iconfont-1 ghzs-gray-highlight' />智能推荐</div>
                            <div className='flex-row'><span className='iconfont-1 ghzs-gray-highlight' />实时保存/预览/导出</div>
                        </div>
                    </div>
                    {/* <div className='login-left-footer'>Copyright © 2023 北京青远生态环境有限公司 版权所有</div> */}
                    <div className='login-left-footer'>北京青远生态环境有限公司提供技术支持</div>

                </div>
            </div>
            <div className='login-right'>
                <div className='login-box'>
                    <div className='login-right-title' style={{ marginBottom: 14 }}>自然保护地规划</div>
                    <div className='login-right-title-system'>智慧辅助系统</div>
                    <div className='flex-row login-right-now' style={{ marginBottom: '51px' }}>已有账号，
                        <div
                            onClick={jumpToLogin}
                            className='flex-row switch-btn'
                        >
                            前往登录
                            <div className='switch-btn-icon-container'>
                                <RightOutlined className='switch-btn-icon' color='#fff' />
                            </div>
                        </div>
                    </div>
                    <Input
                        className='login-right-input'
                        maxLength={11}
                        placeholder="请输入手机号"
                        prefix={<MobileOutlined />}
                        size={'large'}
                        onChange={onPhoneTextChange}
                        value={phone}
                        type={'number'}
                    />
                    <Input
                        className='login-right-input'
                        suffix={
                            <div onClick={handleSendCode} className='send-code-btn'>
                                {
                                    //是否可以继续发送验证码
                                    codeLoading ?
                                        <React.Fragment>
                                            {
                                                //是否在发送中
                                                codeSending ?
                                                    <LoadingOutlined />
                                                    :
                                                    <span>{countTime}秒后获取</span>
                                            }
                                        </React.Fragment>
                                        :
                                        '获取验证码'
                                }
                            </div>
                        }
                        placeholder="请输入验证码"
                        prefix={<SafetyCertificateOutlined />}
                        size={'large'}
                        maxLength={4}
                        onChange={onCodeTextChange}
                        value={code}
                    />
                    <Input
                        className='login-right-input'
                        placeholder="请输入密码"
                        prefix={<LockOutlined />}
                        size={'large'}
                        maxLength={20}
                        onChange={onPasswordTextChange}
                        value={password}
                        type={'password'}
                    />
                    <Checkbox
                        className='login-right-checkbox'
                        onChange={onChange}
                    >
                        注册后自动登录
                    </Checkbox>
                    <Button
                        className='login-right-botton'
                        onClick={handleRegister}
                        type="primary"
                        disabled={!checkLoginBtnEnable()}
                        loading={loginLoading}
                    >
                        立即注册
                    </Button>
                    <div className='login-right-text'>点击<span className='login-right-color'>立即注册</span>表示已阅读并同意<span className='login-right-color'>服务条款</span></div>
                </div>
            </div>
        </div>
    )
}

export default Register;